// pages/live_paper/index.js
import { liveSendMessage,getMessagesList } from '../../api/live.js';
import { getUserInfo } from '../../api/user.js';


import { iphonex } from '../../utils/iphonex.js';

import { formatTime } from '../../utils/util.js';
import { aliOssParams } from '../../utils/oss/oss.js';

const app = getApp();
Page({

  behaviors: [iphonex],
	/**
	 * 页面的初始数据
	 */
	data: {
		/* oss star*/
		ossBaseUrl:'',
		ossAccessid:'',
		ossAccesskey:'',
		fileSize:1024*1024*1000,
		/* oss end*/

		/* 页面基础信息 star*/
		matchName:'',
		matchNameHasMore:false,//赛事名称是否超过一行
		lookNum:0,//观看人数
		announcerInfo:{}, //当前主播信息
		liveId:'',
		matchId:'',
		inputValue:'',
		inputLength:1000, //后台是text
		/* 页面基础信息 end*/

		type:0,//0 观看者  1 主播
		showFun:false,//是否显示功能栏
		scrollIntoView:'', //用于定位指定消息ID
		tempScrollIntoView:'', //用于临时记录指定ID（加载数据后）
		tempPageSize:50, //单次数据请求量（固定，不要删,该值为单次累加条数）
		liveList:[],//聊天列表记录
		selectFun:false, // 是否选择了媒体 避免快速多次点击造成多个弹窗
		isRequest:false, // 是否在请求状态
		isSelectImg:false, //用于处理点击图片/选择媒体后进行了onshow
		scrollAnimation:true,//滚动动画
		bindIndex:'',//点击消息的下标
		scrollTop:0, // scroll-viewTop值
		listTotal:1, //列表总条数
		scrollViewTop:'', //用于判断所播放的视频是否在可视区域
		scrollViewHeight:'', //用于判断所播放的视频是否在可视区域

	},

	// 显示隐藏功能栏
	showFunState(){
		this.setData({showFun:!this.data.showFun});
		this.getScrollHeight();//每次变化时更新
	},

	// 隐藏功能栏
	closeFun(){
		this.setData({showFun:false});
		this.getScrollHeight();//每次变化时更新
	},
	// 功能栏选择功能
	bindFun(e){
		let {index}=e.currentTarget.dataset;
		let {fileSize,selectFun}=this.data;
		if(!selectFun){
			this.data.selectFun=true;
			setTimeout(()=>{
				this.data.selectFun=false;
			},100)
			switch(Number(index)){
				case 0:
					wx.chooseImage({
						count: this.data.uploadFileCount, // 可同时上传的图片数
						sizeType: ['original', 'compressed'],
						sourceType: ['camera','album'],
						success: res => {
							let str = [];
							// console.log(res.tempFiles)
							res.tempFiles.forEach((e,i)=>{
								if(e.size<=fileSize){
									this.pushMessage(e.path,2,(fileName,id)=>{
										this.uploadFileToOss(e.path,fileName,id,2)
									})
								}else{
									str.push(Number(i+1))
								}
								if(i==res.tempFiles.length-1&&str.length>0){
									wx.showModal({
										title: '温馨提示',
										content: `${(str.length==1?'':('第'+str.join(',')+'张图片超出大小限制,'))}图片不能超过${fileSize/1024/1024}M`,
										showCancel:false,//默认是“取消”
										confirmText:"好的"//默认是“确定”
								 })
								}
							})
						},
						complete:res=>{
							this.showFunState()
						}
					})
				break;
				case 1:
					wx.chooseVideo({
						sourceType: ['album','camera'],
						maxDuration: 60,
						camera: 'back',
						success:res=>{
							if(res.size>fileSize){
								wx.showModal({
									title: '温馨提示',
									content: `视频不能超过${fileSize/1024/1024}M`,
									showCancel:false,//默认是“取消”
									confirmText:"好的"//默认是“确定”
							 })
							}else{
								this.pushMessage(res.tempFilePath,3,(fileName,id)=>{
									this.uploadFileToOss(res.tempFilePath,fileName,id,3)
								})
							}
						},
						complete:res=>{
							this.showFunState()
						}
					})
				break;
				default:
				break;
			}
			this.data.isSelectImg = true
		}

	},

	// 视频进入和退出全屏时触发
	bindfullscreenchange(e){
		this.data.isSelectImg=e.detail.fullScreen;
	},

	// 获取文件后缀名称
	getFileName(file){
		return file.substring(file.lastIndexOf("."), file.length);//后缀名
	},
	
	// 追加消息到当前聊天
	pushMessage(title,type=1,callback,state=false){ //   type  //类型 1-文本，2-图片，3-视频 4-接收消息处理   state 追加的消息是否是成功
		let {liveList,announcerInfo} = this.data;
		let id = 'zx'+this.random_string(8);
		let fileName = type==1||type==4?'':this.returnFileName(title);
		let obj = { id:id }
		if(type==4){ // 接收消息
				let {avatar,createTime,message,messageType,username,path,messageId}=title;
				obj.messageId=messageId||id
				obj.createTime=createTime.replace(/-/g,'/');//时间
				obj.username=username; //名称
				obj.messageType=messageType==1?'message':(messageType==2?'image':'video'); //类型 1-文本，2-图片，3-视频
				// obj.state='success'; //状态
				if(messageType==1){
					obj.message=message//文本
				}else{
					obj.path=path// 图片/视频链接
				}
				if(avatar!=this.data.avatar){
					obj.avatar=avatar
				}
				liveList.push(obj)
		}else{ // 主播追加消息
			// console.log(fileName)
			// console.log(title,type)
			obj.messageId=id
			obj.createTime=formatTime(); //时间
			obj.username=announcerInfo.name; //名称
			obj.messageType=type==1?'message':(type==2?'image':'video'); //类型 1-文本，2-图片，3-视频
			state?'':obj.state='loading'
			// obj.state=state?'success':'loading'; //状态
			if(type==1){
				obj.message=title//文本
			}else{
				obj.path=title// 图片/视频链接
				obj.fileName=fileName
			}
			liveList.push(obj);
		}
		this.setData({liveList})
		this.data.tempScrollIntoView=id
		setTimeout(()=>{
			this.setData({scrollIntoView:id})
		},10)
		if(type==1){
			this.setData({inputValue:''})
		}
		callback&&callback((type==4?'':fileName),id)
	},

	// 生成文件名称并返回
	returnFileName(file){
		return `${this.random_string(18)}${this.getFileName(file)}`;
	},

	// 上传文件到oss
	uploadFileToOss(file,fileName,id,type,callback){ //文件路径 文件名称 消息id 类型
		let {ossBaseUrl,ossAccessid}=this.data;
		let obj = aliOssParams()
		let aliKey = `live/${formatTime().split(' ')[0]}/${fileName}`;
		// console.log(aliKey)
		let {liveList} = this.data
		wx.uploadFile({
			url: ossBaseUrl,
			name: 'file',
			filePath: file,
			formData:{
				'key' : aliKey,
				'policy': obj.policy,
				'OSSAccessKeyId': ossAccessid, 
				'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
				'signature': obj.signature
			},
			success:res=>{
				if(res.statusCode==200){
					let path = `https://oss-images.ywxktrip.com/${aliKey}`;
					this._liveSendMessage(path,type,id,resp=>{
						let index = liveList.findIndex((value)=>value.fileName==fileName);//不抽出来是因为是异步
						if(resp.code==0){
							this.setMessageState(id,'success')
							liveList[index].path = path;
							delete liveList[index].fileName;
							this.setData({[`liveList[${index}]`]:liveList[index]})
						}else{
							this.setMessageState(id,'error')
						}
					});
					
				}else{
					this.setMessageState(id,'error')
				}
			},
			fail:err=>{
				console.log(err)
				this.setMessageState(id,'error')
			},
			complete:res=>{
				// console.log(res)
				callback&&callback(res)
			}
		})
	},

	//设置消息发送成功/失败
	setMessageState(id,state='success'){// (消息id，0成功，1失败) state  'success':'error'
		let {liveList}=this.data;
		let index = liveList.findIndex((value)=>value.id==id);
		// 找出对应id在列表的位置
		if(index!=-1){
			if(state=='success'){
				let liveitem = liveList[index]
				delete liveitem.state
				this.setData({[`liveList[${index}]`]:liveitem})

			}else{
				this.setData({[`liveList[${index}].state`]:state})
			}
		}
	},

	// 生成随机数
	random_string(len=32) {
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (let i = 0; i < len; i++) {
		　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return pwd;
	},

	// 获取列表消息
	_getMessagesList(){
		let {liveList,tempPageSize,matchId,isRequest}=this.data
		this.data.isSelectImg=false;
		if(!isRequest){
			this.setData({isRequest: true})
				let page = liveList.length/tempPageSize;
				// console.log(page)
				let requestPageLength = ((page%1==0?Number(page+1):Math.ceil(page))*tempPageSize);
				// console.log(requestPageLength)
				getMessagesList(matchId,{matchId:matchId,pageNum:1,pageSize:requestPageLength}).then(res=>{
					// console.log(res)
						this.setData({isRequest: false})
						if(res.code==0){
							this.data.bindIndex = '';
							this.updateMessageList(res.rows,(arr,id)=>{
								let index = arr.findIndex((value)=>value.id==id);//不抽出来是因为是异步
								this.setData({liveList:arr,scrollIntoView:arr[index>0?index-1:0].id,listTotal:res.total})
								setTimeout(()=>{
									this.setData({scrollAnimation:true})
								},500)
							})
						}
				})
		}
	},

	// 更新列表消息
	updateMessageList(arr,callback){
		let nowAvatar=this.data.avatar;
		let newArr = [];
		let tempid = '';
		let {tempScrollIntoView,liveList}=this.data
		let errMessageArr =liveList.filter(this.checkAdult);
		if(errMessageArr.length>0){//有发送失败的消息处理
			let tempArr = arr.concat(errMessageArr);//合并数组
			tempArr.sort((a,b)=> {return Date.parse(b.createTime.replace(/-/g,"/"))-Date.parse(a.createTime.replace(/-/g,"/"));});
			arr = tempArr
		}
		// error loading
		arr.forEach((e,i)=>{
			let obj = ''
			if(!e.state){//请求回来的数据，不是走这里的说明是发送失败等数据，直接追加
				let {avatar,createTime,message,messageType,username,path}=e;
				let id = 'zx'+this.random_string(8);
				obj = {
					messageId:e.messageId,
					createTime:createTime.replace(/-/g,'/'), //时间
					username:username, //名称
					messageType:messageType==1?'message':(messageType==2?'image':'video'), //类型 1-文本，2-图片，3-视频
					id:id,
					state:'success'
				}
				if(messageType==1){//文本
					obj.message=message
				}else{// 图片/视频链接
					obj.path=path
				}
				if(e.messageId ==tempScrollIntoView||liveList.length==0&&i==0){//定位到指定位置或者首次加载定位时设置
					tempid=id
				}
				if(avatar!=nowAvatar){
					obj.avatar=avatar
				}
			}
			newArr.unshift(e.state?e:obj)
			if(i==arr.length-1){
				callback&&callback(newArr,tempid)
			}
		})
	},
	// 点击消息
	catchMessage(e){
		// console.log(e)
			let {index}=e.currentTarget.dataset
			let {liveList,bindIndex}=this.data
			let {state,messageType}=liveList[index];
			if(state=='error'){
				wx.showActionSheet({
					itemList: ['重新发送','删除消息'],//显示的列表项
					success: res=> {//res.tapIndex点击的列表项
						 if (res.tapIndex==0) {
							//重新发送
							this.againSendMessage(e)
					 }else if(res.tapIndex==1){
						 //删除消息
						liveList.splice(index,1) //在下标1处开始删除,删除一位
						this.setData({liveList:liveList})
					 }
					}
			 })
			}else if(messageType=='image'){//看图片
				this.previewImg(index);
			}else if(messageType=='video'){//看视频
				let videoContext = wx.createVideoContext('q'+liveList[index].id, this); // 为了避免跟整体viewID重名
				// console.log(index)
				if(bindIndex!=index){
					videoContext.play();
				}
				this.setData({bindIndex:index})
			}
	},

	// 消息发送失败二次发送
	againSendMessage(e){
		// console.log(e)
		let {index}=e.currentTarget.dataset
		let {liveList,listTotal}=this.data
		let {messageType,message,path,fileName,id}=liveList[index];
		this.setMessageState(id,'loading');
		if(messageType=='message'){
			this._liveSendMessage(message,1,id,res=>{
				if(res.code==0){
					this.againSetMessage(message,1,id)
					this.setData({listTotal:listTotal-1})
				}
			})
		}else{
			if(path.indexOf("http://tmp") !== -1){//文件上传的时候就失败了
				this.uploadFileToOss(path,fileName,id,messageType=='image'?2:3,res=>{
					if(res.statusCode==200){
						this.againSetMessage(path,messageType=='image'?2:3,id)
					}
				})
			}else{ //文件上传成功，但是发送消息失败了
				if(messageType=='image'){
					this._liveSendMessage(path,2,id,res=>{
						if(res.code==0){
							this.againSetMessage(path,2,id)
						}
					})
				}else{
					this._liveSendMessage(path,3,id,res=>{
						if(res.code==0){
							this.againSetMessage(path,3,id)
						}
					})
				}
			}
		}

	},
	// 消息发送失败后重新更新位置
	againSetMessage(msg,type,id,callback){
		let {liveList}=this.data
		let index = liveList.findIndex((value)=>value.id==id);//加载中下标
		liveList.splice(index,1) //在下标1处开始删除,删除一位
		this.data.liveList = liveList
		this.pushMessage(msg,type,callback,true)
	},
	
	bindtimeupdate(e){
		// console.log(e)
	},

	// 视频播放结束
	bindended(){
		if(!this.data.isSelectImg){ //非全屏下
			this.setData({bindIndex:''})
		}
	},

	// 获取更多消息
	getMoreList(){
		let {liveList,listTotal}=this.data;
		if(listTotal>liveList.length){//判断是否有更多的数据
			this.setData({scrollAnimation:false})
			this._getMessagesList()
			let {messageId} = liveList[0];
			this.data.tempScrollIntoView = messageId;
		}
	},
	checkAdult(item) {//将不是成功状态的获取出来
		return item.state!='success';
	},
	websocketFun(){
		let {webSocketUrl,sessionId} = app.globalData
		let {liveId,type}=this.data
		wx.connectSocket({
      url: `${webSocketUrl}/api/${liveId}/${sessionId}/${type==1}`
		})
		this.getSocketMessage()
	},


	// 获取文本信息
	getValue(e){
		let {inputLength}=this.data;
		if(inputLength>=e.detail.value.trim().length){
			this.setData({inputValue:e.detail.value.trim()})
		}else{
			this.setData({inputValue:e.detail.value.trim().substring(0,inputLength)})
			wx.showToast({
				title: '单次发送消息长度不能超过'+inputLength+'位',
				icon:'none'
			})
		}
	},
	// 发送文本
	sendTextMeaage(){
		let {inputValue}=this.data
			if(inputValue!=''){
				this.pushMessage(inputValue,1,(fileName,id)=>{//追加到列表，返回文件名（音频时返回）id，用于提交成功后数据绑定
				this._liveSendMessage(inputValue,1,id,res=>{
					// console.log(res)
				})
			})
		}
	},

	// 直播发送图文信息
	_liveSendMessage(message,messageType=1,id,callback){ //messageType  1-文本，2-图片，3-视频   不为1时 message传的是path
		let {liveId,matchId,listTotal}=this.data;
		let obj = {liveId:liveId,matchId:matchId,messageType:messageType};
		if(messageType==1){
			obj.message=message
		}else{
			obj.path=message
		}
		liveSendMessage(liveId,obj).then(res=>{
			if(res.code==0){
				this.setData({listTotal:listTotal+1});//不管是文本，图片，视频，成功失败，只要是成功的时候，都会走这里，所以消息条数在此+1
				this.setMessageState(id,'success')
			}else{
				this.setMessageState(id,'error')
			}
			callback&&callback(res)
		}).catch(err=>{
			console.log(err)
			this.setMessageState(id,'error')
		})
	},
	// 获取用户信息
	_getUserInfo(){
		getUserInfo().then(res=>{
			if(res.code==0){
				let {announcer,user}=res.data;
				this.data.announcerInfo = announcer;
				let {avatar}=user;
				this.data.avatar = avatar;
			}
		})
	},

	getSocketMessage(){
		wx.onSocketMessage(data=>{
			let message = JSON.parse(data.data)
			this.setData({lookNum:message.lookNum})
			let {avatar}=this.data
			if(message.avatar!=avatar){
				this.pushMessage(message,4,res=>{
					// console.log(res)
				})
			}
		})
	},

	// 图片全屏预览
	previewImg(index){
		let {liveList}=this.data
		if(liveList[index].hasOwnProperty('state')&&liveList[index].state=='loading'){ //有状态标识
			wx.showToast({
				title: '消息发送结束才能预览',
				icon:'none'
			})
		}else{
			this.data.isSelectImg=true;
			let arr = [];
			liveList.forEach((e,i)=>{
				if(e.messageType=='image'&&(!e.hasOwnProperty('state')||e.state=='success')){ //是图片，没有状态标识
					if(e.path==liveList[index].path){
						index=arr.length
					}
					arr.push(e.path)
				}
				if(i==liveList.length-1){
					app.previewImg(arr,index)
				}
			})
		}

	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		// console.log(options)
		if(options.hasOwnProperty('scene')){
			options = options.scene
		}
		let {liveId,matchId,matchName,lookNum,type}=options
		let {baseUrl,accessid,accesskey} = app.globalData.oss;
		this.setData({ossBaseUrl:baseUrl,ossAccessid:accessid,ossAccesskey:accesskey})
		if(liveId&&type!=''){
			this.setData({ liveId,matchId,matchName,lookNum:Number(lookNum)+1,type })
				const query = wx.createSelectorQuery().in(this)
				query.select('.match_name').boundingClientRect(res=>{
					this.setData({matchNameHasMore:res.height>30})
				}).select('.center_message').boundingClientRect(res=>{
					this.data.scrollViewTop = res.top
				}).exec()
				this.getScrollHeight();
		}else{
			wx.navigateBack()
		}
		this.websocketFun()
		if(type==1){
			this._getUserInfo()
			let {liveShowNetworkTips}=app.globalData;
			if(liveShowNetworkTips){
				wx.showModal({
					title: '温馨提示',
					content: '请在网络环境良好的环境下直播，避免直播卡顿',
					cancelText:'好的',//默认是“取消”
					confirmColor: '#000',//确定文字的颜色
					confirmText:"不再提示",//默认是“确定”
					confirmColor: '#000',//确定文字的颜色
					success: function (res) {
						if (res.confirm) {
							app.globalData.liveShowNetworkTips=false
						}
				 }
			 })
			}
		}
	},

	// 获取scroll-view高度
	getScrollHeight(callback){
		wx.createSelectorQuery().in(this).select('.center_message').boundingClientRect(res=>{
			this.data.scrollViewHeight = res.height;
			callback&&callback(res.height)
		}).exec()
	},

	catchtouchmove(e){
		return false;
	},

	//页面滚动事件
	bindscroll(e){
		if(e.detail.scrollTop<50){
			this.setData({scrollTop:0})
			this.getMoreList()
		}
		let {bindIndex,liveList,scrollViewTop,scrollViewHeight}=this.data;
		if(bindIndex!=''){
			let {id}=liveList[bindIndex];
			wx.createSelectorQuery().in(this).select('#q'+id).boundingClientRect(res=>{
				let {top,height}=res;
				if(top+height<scrollViewTop||scrollViewTop+scrollViewHeight<top+height){
					wx.createVideoContext('q'+id, this).stop()
				}
			}).exec()
		}
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		if(!this.data.isSelectImg){
			this._getMessagesList()
		}
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {
		wx.closeSocket({code: 1000})
		var pages = getCurrentPages();
		var prevPage = pages[pages.length - 2];  //上一个页面
		prevPage.setData({[`lists[${prevPage.data.bindIndex}].lookNum`]:Number((this.data.lookNum-1)>=0?(this.data.lookNum-1):0)});//设置数据

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {
		let { liveId,matchId,matchName,num}=this.data
		var shareObj = {
			path: `/pages/live_paper/index?liveId=${liveId}&matchId=${matchId}&matchName=${matchName}&lookNum=${num}&type=0`,
			success: function (res) {// 转发成功之后的回调
				if (res.errMsg == 'shareAppMessage:ok') { }
			}
		};
		return shareObj;
	}
})